<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/11 0011
 * Time: 12:01
 */

namespace app\index\model;


use think\Exception;
use think\Model;

class Gcategory extends Model
{
    protected $pk = 'cate_id';
    public static function getGcategory($get='')
    {
        $field=[
            'cate_id',
            'cate_name',
            'parent_id',
            'sort_order',
            'if_show'
        ];
        $model=self::field($field)
            ->where('parent_id',$get)
            ->select()->order('sort_order')->toArray();
        foreach ($model as $k=>$v){
            $model[$k]['child']=1;
            $child=self::field(true)
                ->where('parent_id',$v['cate_id'])
                ->find();
            if(is_null($child)){
                $model[$k]['child']=0;
            }
        }
        return $model;
    }

    public static function getGcategory2()
    {
        $sql=self::alias('n')
            ->field('cate_id')
            ->whereColumn('n.parent_id','=','w.cate_id')
            ->limit(1)
            ->buildSql();
        return self::alias('w')
            ->field('cate_id,cate_name,parent_id,sort_order')
            ->field("if(".$sql.",1,0) as has_next")
            ->where('w.parent_id',$id)
            ->select();
    }

    public function cateAdd(array $data, array $allowField = [], bool $replace = false)
    {
        try{
            if(empty($data)){
                $this->error = '新增数据不能为空！';
                return ;
            }
            // 限制写入的字段列表
            if (!empty($allowField))
                $this->allowField($allowField);
            $this->replace($replace)->save($data);

            return true;
        }catch (Exception $ex){
            $this->error = $ex->getMessage();
            return false;
        }
    }
    public function getInsertId(){// 获取id的方法
        $data = $this->toArray();
        return $data[$this->pk];
    }

    public function changecate($data, $where = [], $allowField = [])
    {
        try{
            if (empty($data)){
                $this->error = "修改数据不能为空!!";
                return;
            }
            if (!empty($allowField)){
                $this->allowField($allowField);

            }
            if (!empty($where)){
                $this->setUpdateWhere($where);
                if (isset($data[$this->pk]))  unset($data[$this->pk]);
            }
            return $this->exists(true)->save($data);

        }catch (Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
}